package com.example.erat.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.erat.common.BusinessException;
import com.example.erat.common.FileUtils;
import com.example.erat.dto.SubmissionQueryDTO;
import com.example.erat.entity.Experiment;
import com.example.erat.entity.Submission;
import com.example.erat.mapper.SubmissionMapper;
import com.example.erat.service.ExperimentService;
import com.example.erat.service.SubmissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class SubmissionServiceImpl extends ServiceImpl<SubmissionMapper, Submission> implements SubmissionService {

    @Value("${erat.upload.path}")
    private String uploadPath;

    @Autowired
    private ExperimentService experimentService;

    @Override
    public void submitExperiment(int studentId, int experimentId, MultipartFile file) {
        // 检查实验是否存在
        Experiment experiment = experimentService.getById(experimentId);
        if (experiment == null) {
            throw new BusinessException("实验不存在");
        }

        // 检查是否已截止
        boolean isOverdue = new Date().after(experiment.getDeadline());

        // 构建存储路径
        int courseId = experiment.getCourseId();
        String filePath = uploadPath + File.separator + courseId + File.separator + experimentId + File.separator + studentId;
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + fileExtension;

        // 保存文件
        try {
            File dest = new File(filePath + File.separator + fileName);
            file.transferTo(dest);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw new BusinessException("文件上传失败");
        }

        // 保存提交记录
        Submission submission = new Submission();
        submission.setStudentId(studentId);
        submission.setExperimentId(experimentId);
        submission.setFileName(originalFilename);
        submission.setFilePath(filePath + File.separator + fileName);
        submission.setFileSize(file.getSize());
        submission.setSubmitTime(new Date());
        submission.setIsOverdue(isOverdue);

        this.save(submission);
    }

    @Override
    public List<Submission> getSubmissionList(SubmissionQueryDTO queryDTO) {
        LambdaQueryWrapper<Submission> wrapper = new LambdaQueryWrapper<>();
        
        if (queryDTO.getStudentId() != 0) {
            wrapper.eq(Submission::getStudentId, queryDTO.getStudentId());
        }
        
        if (queryDTO.getExperimentId() != 0) {
            wrapper.eq(Submission::getExperimentId, queryDTO.getExperimentId());
        }
        
        if (queryDTO.getStatus() != null) {
            switch (queryDTO.getStatus()) {
                case "submitted":
                    wrapper.isNotNull(Submission::getSubmitTime);
                    break;
                case "notSubmitted":
                    wrapper.isNull(Submission::getSubmitTime);
                    break;
                case "overdue":
                    wrapper.eq(Submission::getIsOverdue, true);
                    break;
                case "graded":
                    wrapper.isNotNull(Submission::getScore);
                    break;
            }
        }
        
        return this.list(wrapper);
    }

    @Override
    public void gradeSubmission(String submissionId, Integer score, String feedback) {
        Submission submission = this.getById(submissionId);
        if (submission == null) {
            throw new BusinessException("提交记录不存在");
        }
        
        submission.setScore(score);
        submission.setFeedback(feedback);
        
        this.updateById(submission);
    }

    @Override
    public void downloadFile(String submissionId, HttpServletResponse response) {
        Submission submission = this.getById(submissionId);
        if (submission == null) {
            throw new BusinessException("文件不存在");
        }
        
        File file = new File(submission.getFilePath());
        if (!file.exists()) {
            throw new BusinessException("文件不存在");
        }
        
        FileUtils.downloadFile(file, response);
    }
}    